<!--//This file is part of the store/retrieve project
//    (http://code.google.com/p/storeretrieve/).
//
//    Store/retrieve is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Store/retrieve is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with store/retrieve. If not, see <http://www.gnu.org/licenses/>.
//-->


<%@ page contentType="text/html; charset=UTF-8" %>  
<html>

<%@ page import="javax.servlet.http.HttpServletRequest,
		java.util.Properties,
		java.util.ArrayList,
		java.io.File,
		java.io.FileInputStream,
		org.w3c.dom.*,
		javax.xml.parsers.*,
		javax.xml.xpath.*,
		java.util.HashMap,
		java.lang.StringBuilder"
%>

<%@include file="includes/tools.jsp" %>
<%@include file="includes/backend.jsp" %>

<%! 	
	Properties props;
	String responseString = "";

	String getDefaultValue(HttpServletRequest request, String key) {
		if(request.getParameter(key) == null) 
			return "";
		return request.getParameter(key);
	}

	String response(javax.servlet.http.HttpServletRequest request) {
		StringBuilder o = new StringBuilder();
		String wildcard = "";		
		if(request.getParameterValues("wildcard") != null && request.getParameterValues("wildcard")[0].equals("auto"))
			wildcard = ".*";

		if(request.getParameter("origin") != null && request.getParameter("origin").equals("query")) {
			HashMap queryParms = new HashMap();
			if(!request.getParameter("Id").equals("")) queryParms.put("Storage/Id", wildcard + request.getParameter("Id") + wildcard);
			if(!request.getParameter("ForeignId").equals(""))queryParms.put("Storage/ForeignId", wildcard + request.getParameter("ForeignId") + wildcard);
			if(!request.getParameter("ImportDate").equals(""))queryParms.put("Meta/ImportDate", wildcard + request.getParameter("ImportDate") + wildcard);
			if(!request.getParameter("DocumentDate").equals(""))queryParms.put("Meta/DocumentDate", wildcard + request.getParameter("DocumentDate") + wildcard);
			if(!request.getParameter("ProcessedDate").equals(""))queryParms.put("Meta/ProcessedDate", wildcard + request.getParameter("ProcessedDate") + wildcard);
			if(!request.getParameter("Sender").equals(""))queryParms.put("Meta/Sender", wildcard + request.getParameter("Sender") + wildcard);
			if(!request.getParameter("Receiver").equals(""))queryParms.put("Meta/Receiver", wildcard + request.getParameter("Receiver") + wildcard);
			if(!request.getParameter("Subject").equals(""))queryParms.put("Meta/Subject", wildcard + request.getParameter("Subject") + wildcard);
			if(!request.getParameter("Description").equals(""))queryParms.put("Meta/Description", wildcard + request.getParameter("Description") + wildcard);
			if(!request.getParameter("Tags").equals(""))queryParms.put("Meta/Tags", wildcard + request.getParameter("Tags") + wildcard);
			if(!request.getParameter("Keywords").equals(""))queryParms.put("Meta/Keywords", wildcard + request.getParameter("Keywords") + wildcard);
			
			ArrayList<File> matches = query(props.getProperty("INTERNAL_REPO_PATH"), queryParms);
			o.append(matches.size() + " matches.");
			if(matches.size() > 0) {
				o.append("<hr />");
				o.append("<table border=\"1\" bordercolor=\"\" style=\"background-color:\" width=\"100%\" cellpadding=\"1\" cellspacing=\"1\">");
				o.append("<tr><td>Container</td><td>Import date</td><td>Document date</td><td>Sender</td><td>Receiver</td><td>Subject</td></tr>");
				for(File f : matches) {
					o.append(getTableLineByContainer(f));
				}
			}
			

		} else {
			o.append("Please start new query.");		
		}
			
		return o.toString();
	}

	String getTableLineByContainer(File container) {
		StringBuilder o = new StringBuilder();
		o.append("<tr>");	
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(new File(container.getAbsolutePath() + "/meta.xml"));
			doc.getDocumentElement().normalize();

			o.append("<td>");
			o.append(getIconLink("document-open", 
				props.getProperty("EXTERNAL_FOLDER_VIEW_URL_TEMPLATE").replaceAll("\\*",  
				new File(props.getProperty("INTERNAL_REPO_PATH")).toURI().relativize(container.toURI()).getPath().replaceAll("/$", "")),
				"_parent"));
                        o.append(getIconLink("x-office-document",
				("view.jsp?id=" + getFieldValueFromMetaDOM(doc, "Storage/Id")),
                                "_self"));
                        o.append(getIconLink("edit-select-all",
				("edit.jsp?id=" + getFieldValueFromMetaDOM(doc, "Storage/Id")),
                                "_self"));
                        o.append("</td>");
			

			o.append("<td>");
			o.append(getFieldValueFromMetaDOM(doc, "Meta/ImportDate"));
			o.append("&nbsp;</td>");

			o.append("<td>");
			o.append(getFieldValueFromMetaDOM(doc, "Meta/DocumentDate"));
			o.append("&nbsp;</td>");

			o.append("<td>");
			o.append(getFieldValueFromMetaDOM(doc, "Meta/Sender"));
			o.append("&nbsp;</td>");

			o.append("<td>");
			o.append(getFieldValueFromMetaDOM(doc, "Meta/Receiver"));
			o.append("&nbsp;</td>");

			o.append("<td>");
			o.append(getFieldValueFromMetaDOM(doc, "Meta/Subject"));
			o.append("&nbsp;</td>");

		} catch(Throwable ex) { 
			 o.append("Error");
			 ex.printStackTrace();
		} finally {}
			
		o.append("</tr>");	
		return o.toString();
	}

%>

<% 
	request.setCharacterEncoding("UTF-8");
	props = loadPropertiesByUser(request.getRemoteUser()); 

	if(props == null) {
		response.sendRedirect("login.jsp");
	} else {
		responseString = response(request);
	}

%>


<head>
<title>store/retrieve query client</title>
<link rel="stylesheet" type="text/css" href="resources/<%= props.getProperty("CSS") %>" /> 
<link rel="icon" href="resources/logo-storeretrieve-favicon.png" type="image/png" />
</head>
<body>
<%= getLogoHtml() %>
<form method="post" accept-charset="UTF-8" action="query.jsp">
<table border="0" width="" cellpadding="2" cellspacing="2">
	<tr>
		<td>ID</td>
		<td><input type="text" name="Id" size="50" value="<%= getDefaultValue(request, "Id") %>"></td>
	</tr>
	<tr>
		<td>Foreign ID</td>
		<td><input type="text" name="ForeignId" size="50" value="<%= getDefaultValue(request, "ForeignId") %>"></td>
	</tr>
	<tr>
		<td>Import date</td>
		<td><input type="text" name="ImportDate" size="10" value="<%= getDefaultValue(request, "ImportDate") %>"></td>
	</tr>
	<tr>
		<td>Document date</td>
		<td><input type="text" name="DocumentDate" size="10" value="<%= getDefaultValue(request, "DocumentDate") %>"></td>
	</tr>
	<tr>
		<td>Processed date</td>
		<td><input type="text" name="ProcessedDate" size="10" value="<%= getDefaultValue(request, "ProcessedDate") %>"></td>
	</tr>
	<tr>
		<td>Sender</td>
		<td><input type="text" name="Sender" size="50" value="<%= getDefaultValue(request, "Sender") %>"></td>
	</tr>
	<tr>
		<td>Receiver</td>
		<td><input type="text" name="Receiver" size="50" value="<%= getDefaultValue(request, "Receiver") %>"></td>
	</tr>
	<tr>
		<td>Subject</td>
		<td><input type="text" name="Subject" size="50" value="<%= getDefaultValue(request, "Subject") %>"></td>
	</tr>
	<tr>
		<td>Description</td>
		<td><input type="text" name="Description" size="50" value="<%= getDefaultValue(request, "Description") %>"></td>
	</tr>
	<tr>
		<td>Tags</td>
		<td><input type="text" name="Tags" size="50" value="<%= getDefaultValue(request, "Tags") %>"></td>
	</tr>
	<tr>
		<td>Keywords</td>
		<td><input type="text" name="Keywords" size="50" value="<%= getDefaultValue(request, "Keywords") %>"></td>
	</tr>
</table>
<input type="hidden" name="origin" value="query">
<input type="submit" value="Query"> <input type="reset" value="Reset">
<input type="checkbox" name="wildcard" value="auto" <% if(request.getParameterValues("wildcard") != null && request.getParameterValues("wildcard")[0].equals("auto")) out.print("checked=\"checked\""); %>> Implicit wildcard
</form>
<hr />
<%= responseString %>
</body>
</html>
